package com.lerning.edu.manage.controller;

import com.lerning.edu.commons.util.DateUtil;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.services.CampusDSRService;
import com.lerning.edu.services.DSRMonthKPIService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangwei
 * @since 18/6/26
 */
@Component
@EnableScheduling
public class LockDSRTimerByKPIController {
    private static Logger log = LoggerFactory.getLogger(LockDSRTimerByKPIController.class);

    @Autowired
    private DSRMonthKPIService dsRMonthKPIService;
    @Autowired
    private CampusDSRService campusDSRService;

    /***
     * DSR月度KPI达成
     * 每周五凌晨0点25分执行(周五推送的报表)
     * 周一:MON,周二:TUE,周三:WED,周四:THU,周五:FRI,周六:SAT,周日:SUN
     * MON-FRI: 周一至周五
     */
    @Scheduled(cron = "0 25  0 ? * FRI")
    public void dsrByCampusKpiForFRI() {
        //获取前一天年月日
        String lastDate = DateUtil.getLastDateStr1() + " 23:59:59";

        //根据 前一天年月 查询当前财务月开始可结束时间
        Map dqd = new HashMap();
        dqd.put("dqDay", lastDate.subSequence(0, 7));

        List FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dqd);//当前月
        Map dateMap = (HashMap) FinanceMonthOfDq.get(0);

        //财务月的后一个周五跟财务月最后一天在同一个月,则锁定下个财务月的数据
        if (DateUtil.compare_date(dateMap.get("EndDate").toString(), lastDate)) {
            dateMap.put("dqDay", DateUtil.addMonth(lastDate).substring(0,7));
            FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dateMap);//当前月
            dateMap = (HashMap) FinanceMonthOfDq.get(0);
        }

        queryData(dateMap, lastDate);

        log.info("锁定成功!!!" + new Date());
    }

    /***
     * DSR月度KPI达成
     * 每周一凌晨0点25分执行(周一推送的报表)
     */
    @Scheduled(cron = "0 25 0 ? * MON")
    public void dsrByCampusKpiForMON() {
        //获取前一天年月日
        String lastDate = DateUtil.getLastDateStr1() + " 23:59:59";

        //获取前三天的时间
        String lastTheDate = DateUtil.getLastDateStrN(3)+ " 23:59:59";

        //跨财务月时计算数据锁定日期
        Map dqd = new HashMap();
        dqd.put("dqDay", lastTheDate.subSequence(0, 7));
        List FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dqd);//当前月
        Map dateMap = (HashMap) FinanceMonthOfDq.get(0);

        Map dqd1 = new HashMap();
        dqd1.put("dqDay", lastDate.subSequence(0, 7));
        List FinanceMonthOfDq1 = campusDSRService.queryNatureMonthOfDq(dqd1);//当前月
        Map dateMap1 = (HashMap) FinanceMonthOfDq1.get(0);

        //财务月的后一个周五跟财务月最后一天在同一个月,则锁定下个财务月的数据
        if (DateUtil.compare_date(dateMap1.get("EndDate").toString(), lastTheDate)) {
            dateMap.put("dqDay", DateUtil.addMonth(lastTheDate).substring(0,7));
            FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dateMap);//当前月
            dateMap = (HashMap) FinanceMonthOfDq.get(0);
        }

        if (!DateUtil.compare_date(dateMap.get("EndDate").toString(), lastDate)) {
            lastDate = dateMap.get("EndDate").toString();
        }
        //跨财务月时计算数据锁定日期

        queryData(dateMap, lastDate);

        log.info("锁定成功!!!" + new Date());
    }

    /***
     * 锁定数据的方法
     * @param dateMap
     * @param lastDate
     */
    private void queryData(Map dateMap, String lastDate) {
        Map map = new HashMap();

        map.put("BeginDate", dateMap.get("BeginDate").toString());
        map.put("EndDate", lastDate);

        List depars = campusDSRService.queryDepartList();
        List monthKpis = new ArrayList();

        BigDecimal totalMkt = new BigDecimal("0");//mkt渠道业绩汇总
        BigDecimal totalKPIMkt = new BigDecimal("0");// mkt渠道KPI汇总

        BigDecimal totalRef = new BigDecimal("0");//ref渠道业绩汇总
        BigDecimal totalKPIRef = new BigDecimal("0");// ref渠道KPI汇总

        BigDecimal totalRenew = new BigDecimal("0");//renew渠道业绩汇总
        BigDecimal totalKPIRenew = new BigDecimal("0");// renew渠道KPI汇总

        if (depars.size() > 0) {
            for (Object obj : depars) {
                Map dmap = (HashMap) obj;
                map.put("CampusID", dmap.get("cID"));
                map.put("text", lastDate.substring(0, 7));
                map.put("cAddress", dmap.get("cAddress"));

                BigDecimal mktKpi = new BigDecimal("0");//mkt渠道pki
                BigDecimal refKpi = new BigDecimal("0");//ref渠道pki
                BigDecimal renewKpi = new BigDecimal("0");//renew渠道pki

                //查询完成业绩
                Map monthKpi = dsRMonthKPIService.queryAll(map);
                monthKpi.put("CampusID", dmap.get("cID"));
                monthKpi.put("text", lastDate.substring(0, 10));
                monthKpi.put("cAddress", dmap.get("cAddress"));
                //查询18年提前续费的业绩
                Map odsReNewByMonth = dsRMonthKPIService.queryRenewByCmpus(map);

                BigDecimal enrollmint = new BigDecimal("0");
                if (odsReNewByMonth != null) {
                    enrollmint = new BigDecimal(odsReNewByMonth.get("enrollmint").toString());
                }

                //查询指标
                List odsCampusKpi = dsRMonthKPIService.queryCampusKpi(map);

                //加上18年提前分摊的业绩
                BigDecimal renew = new BigDecimal(monthKpi.get("tash").toString()).add(enrollmint);
                monthKpi.put("renew", renew);

                //取到对应渠道的指标
                if (odsCampusKpi.size() > 0) {
                    for (Object campusKpi : odsCampusKpi) {
                        Map mapKpi = (HashMap) campusKpi;
                        if (mapKpi.get("KpiType").equals("MKT")) {
                            mktKpi = new BigDecimal(mapKpi.get("KpiValue").toString());
                            monthKpi.put("mktKpi", mktKpi);
                        } else if (mapKpi.get("KpiType").equals("REF")) {
                            refKpi = new BigDecimal(mapKpi.get("KpiValue").toString());
                            monthKpi.put("refKpi", refKpi);
                        } else if (mapKpi.get("KpiType").equals("ReNew")) {
                            renewKpi = new BigDecimal(mapKpi.get("KpiValue").toString());
                            monthKpi.put("renewKpi", renewKpi);
                        }
                    }
                }else{
                    monthKpi.put("mktKpi", 0.00);
                    monthKpi.put("refKpi", 0.00);
                    monthKpi.put("renewKpi", 0.00);
                }
                //汇总渠道业绩(按校区)
                BigDecimal totalEnrollmentByCampus = new BigDecimal(monthKpi.get("allash").toString()).add(enrollmint);
                monthKpi.put("totalEnrollmentByCampus", totalEnrollmentByCampus);
                //汇总渠道指标(按校区)
                BigDecimal totalKPIByCampus = mktKpi.add(refKpi).add(renewKpi);
                monthKpi.put("totalKPIByCampus", totalKPIByCampus);

                //计算达标率

                if (StringUtil.divideValue(mktKpi)) {
                    monthKpi.put("mktRate", new BigDecimal(monthKpi.get("mash").toString()).divide(mktKpi, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
                } else {
                    monthKpi.put("mktRate", 0.0);
                }
                //ref
                if (StringUtil.divideValue(refKpi)) {
                    monthKpi.put("refRate", new BigDecimal(monthKpi.get("fash").toString()).divide(refKpi, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
                } else {
                    monthKpi.put("refRate", 0.0);
                }
                //renew
                if (StringUtil.divideValue(renewKpi)) {
                    monthKpi.put("renewRate", renew.divide(renewKpi, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
                } else {
                    monthKpi.put("renewRate", 0.0);
                }
                //
                if (StringUtil.divideValue(totalKPIByCampus)) {
                    monthKpi.put("totalRate", totalEnrollmentByCampus.divide(totalKPIByCampus, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
                } else {
                    monthKpi.put("totalRate", 0.0);
                }
                //汇总渠道目标值
                totalKPIMkt = totalKPIMkt.add(mktKpi);
                totalKPIRef = totalKPIRef.add(refKpi);
                totalKPIRenew = totalKPIRenew.add(renewKpi);
                //汇总渠道业绩值
                totalMkt = totalMkt.add(new BigDecimal(monthKpi.get("mash").toString()));
                totalRef = totalRef.add(new BigDecimal(monthKpi.get("fash").toString()));
                totalRenew = totalRenew.add(renew);

                monthKpis.add(monthKpi);
            }

            int insertDsrMonthKPI = dsRMonthKPIService.insertDsrMonthKPI(monthKpis);
        }
    }
}
